package xkp.lesson2;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class Client {
    public static void main(String[] args) throws IOException {
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.configureBlocking(false);



        //socketChannel.
        //ByteBuffer buffer = ByteBuffer.allocate(1024);
        //read会阻塞
        //配置为非阻塞
        Selector selector = Selector.open();
        socketChannel.register(selector,SelectionKey.OP_CONNECT);

        socketChannel.connect(new InetSocketAddress("127.0.0.1",8888));


        while(true){
            //监听事件到来
            selector.select();
            Set selectedKeys = selector.selectedKeys();
            Iterator<SelectionKey> keyIterator = selectedKeys.iterator();
            while(keyIterator.hasNext()) {
                SelectionKey key = keyIterator.next();
                if(key.isAcceptable()) {
                    System.out.println("1");
                } else if (key.isConnectable()) {
                    System.out.println("2");
                    SocketChannel channel = (SocketChannel) key.channel();
                    System.out.println(channel.getRemoteAddress()+"连接成功");
                    //keyIterator.remove();
                } else if (key.isReadable()) {
                    System.out.println("3");
                    // a channel is ready for reading
                } else if (key.isWritable()) {
                    System.out.println("4");
                    // a channel is ready for writing
                }
                keyIterator.remove();
            }
        }
        //当配置为非阻塞的话，面临的问题为 此处通道不管读还是没读到数据，都不会阻塞，如何和得知读到数据?????
       /* socketChannel.read(buffer);
        System.out.println("------------------------");*/
    }
}
